package com.houserent.service;

import com.houserent.domain.House;

/**
 * HouseService.java 【业务层】
 * 定义House[] 保存House对象
 * 1. 响应HouseView的调用
 * 2. 完成对房屋信息的各种操作(增删改查c[create]r[read]u[update]d[delete])
 */

public class HouseService {
    private House[] houses; // 保存House对象

    private int houseNums = 1; // 记录当前有多少个房屋信息
    private int idCounter = 1; // 记录当前的id增长到哪个值
    public HouseService(int size) {
        houses = new House[size]; // 创建HouseService对象，指定数组大小

        // 用于测试列表信息
        houses[0] = new House(1, "Jack", "112", "海淀区", 2000, "未出租");

    }

    // search house[i] by address
    public boolean search(String searchAddress) {
        int index = -1;
        for (int i = 0; i < houseNums; i++) {
            if (searchAddress.equals(houses[i].getAddress())) {
                System.out.println(houses[i]);
                index = i;
            }
        }

        if (index == -1) {
            return false;
        }
        return true;
    }

    // delete house[i] by Id
    public boolean del(int delId) {
        int index = -1;
        for (int i = 0; i < houseNums; i++) {
            if (delId == houses[i].getId()) {
                index = i;
            }
        }

        if (index == -1) {
            return false;
        }

        for (int i = index; i < houseNums - 1; i++) {
            houses[i] = houses[i + 1];
        }

        houses[--houseNums] = null;
        return true;
    }

    // 添加新对象，返回boolean值
    public boolean add(House newHouse) {
        if (houseNums == houses.length) {
            System.out.println("数组已满，无法再新加。");
            return false;
        }

        houses[houseNums++] = newHouse;
        newHouse.setId(++idCounter);
        return true;
    }

    // list方法，返回Houses数组
    public House[] list() {
        return houses;
    }

    public House returnObjectById(int id) {
        for (int i = 0; i < houseNums; i++) {
            if (houses[i].getId() == id) {
                return houses[i];
            }
        }
        return null;
    }

}
